package com.g4m.baselib.tool;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.StringTokenizer;

/**
 * 获取用户端信息类
 * Created on 2020-01-01
 * <p>Copyright 2008-2020 snsndk.com</p>
 *
 *  hudesen[hudesen@hudesen.com]
 */
@Slf4j
public class ClientInfo {
    /**
     * 获取客户端ip地址
     *
     * @param request HttpServletRequest
     * @return String ip地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String unknown = "unknown";
        String ips = request.getHeader("x-forwarded-for");
        if (ips == null || ips.length() == 0 || unknown.equalsIgnoreCase(ips)) {
            ips = request.getHeader("Proxy-Client-IP");
        }
        if (ips == null || ips.length() == 0 || unknown.equalsIgnoreCase(ips)) {
            ips = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ips == null || ips.length() == 0 || unknown.equalsIgnoreCase(ips)) {
            ips = request.getRemoteAddr();
        }
        StringTokenizer st = new StringTokenizer(ips, ",; \t\n\r\f");
        String ip = "";
        if (st.hasMoreTokens()) {
            ip = st.nextToken();
        }
        return ip;
    }

    /**
     * 增加跨域
     *
     * @param httpRequest  HttpServletRequest
     * @param httpResponse HttpServletResponse
     */
    public static void addCrossDomain(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
        String crossDomain = httpRequest.getHeader("crossDomain");
        //增加跨域请求
        String origin = "*";
//        if (crossDomain != null && BooleanUtils.toBoolean(crossDomain)) {
        try {
//            origin = httpRequest.getHeader("Origin");
        } catch (Exception ignore) {
        }
//        }
        httpResponse.setHeader("Access-Control-Allow-Origin", origin);
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        httpResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,token");
    }
}
